package com.bjpowernode.mvc.exception;

import com.bjpowernode.common.enums.RespCode;
import com.bjpowernode.mvc.model.result.CommonResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    //@RestControllerAdvice注解的作用：捕获全局异常

    /**
     * 处理Bean Validation验证异常
     *
     * @param bindException 绑定异常
     * @return
     */
    @ExceptionHandler({BindException.class})
    public CommonResult doBeanValidationFail(BindException bindException) {
        //获取发生异常的字段和错误提示
        List<FieldError> fieldErrors = bindException.getFieldErrors();

        List<Map<String, String>> mapList = fieldErrors.stream().map(fieldError -> {
            Map<String, String> map = new HashMap<>();
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
            return map;
        }).toList();
        return CommonResult.warn(RespCode.REQUEST_PARAM_ERR, mapList);
    }

    /**
     * 自定义异常处理
     *
     * @param bizException
     * @return
     */
    @ExceptionHandler({BizException.class})
    public CommonResult doBeanValidationFail(BizException bizException) {
        CommonResult commonResult = new CommonResult(bizException.getCode(), bizException.getMessage());
        return commonResult;
    }


    //其他异常处理
    @ExceptionHandler
    public CommonResult doOtherException(Exception e) {
        //记录日志
        System.out.println("发生了其他异常" + e.getMessage());
        //打印异常的堆栈信息，并指明错误原因
        e.printStackTrace();
        return new CommonResult(RespCode.FAIL.getCode(), e.getMessage());
    }
}
